'use strict';

(function(){
  // Skip overlay on search page to avoid intercepting the main CTA
  try{ if((location.pathname||'').toLowerCase().indexOf('search.html')!==-1){ return; } }catch(e){}
  const LABEL = '用此颜色搜索音乐';
  let overlayBtn = null, lastRect = null;

  function createOverlay(){
    if(overlayBtn) return overlayBtn;
    const btn = document.createElement('button');
    btn.id = 'rt-overlay-color-search';
    btn.type = 'button';
    btn.innerText = '';
    btn.setAttribute('aria-label', LABEL);
    Object.assign(btn.style, {
      /* hard-hide by default to avoid stray dot at (0,0) when theme CSS enforces button min-sizes */
      display: 'none',
      opacity: '0',
      minWidth: '0', minHeight: '0',
      boxShadow: 'none', outline: 'none', WebkitAppearance: 'none', appearance: 'none',
      pointerEvents: 'none',

      position: 'fixed',
      left: '0px', top: '0px', width: '0px', height: '0px',
      zIndex: '2147483647',
      background: 'transparent', color: 'transparent',
      border: 'none',
      padding: '0',
      margin: '0',
      cursor: 'pointer'
    });
    btn.addEventListener('click', function(e){
      e.preventDefault();
      e.stopPropagation();
      // Trigger our navigate function if available; otherwise set flag for summary script
      try { window.__rtGoColorSummary && window.__rtGoColorSummary(); } catch(e){}
      // Set a fallback flag; summary script will read it
      localStorage.setItem('rt_force_go_color_summary', '1');
      // Don't let underlying button receive the click
      return false;
    }, true);
    document.body.appendChild(btn);
    overlayBtn = btn;
    return btn;
  }

  function findTextRects(){
    const results = [];
    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null);
    let node;
    while(node = walker.nextNode()){
      const t = (node.textContent||'').replace(/\s+/g, '');
      if(t.indexOf(LABEL) !== -1){
        const rng = document.createRange();
        rng.selectNodeContents(node);
        const rects = Array.from(rng.getClientRects());
        results.push(...rects);
      }
    }
    return results;
  }

  function updateOverlay(){
    const btn = createOverlay();
    const rects = findTextRects();
    const rect = rects.sort((a,b)=> (b.width*b.height) - (a.width*a.height))[0];
    if(!rect){
      // Hide overlay if not found
      btn.style.width='0px'; btn.style.height='0px';
      btn.style.display='none';
      btn.style.pointerEvents='none';
      return;
    }
    if(lastRect && rect.width===lastRect.width && rect.height===lastRect.height && rect.left===lastRect.left && rect.top===lastRect.top){
      return; // nothing changed
    }
    lastRect = rect;
    btn.style.left = (rect.left + window.scrollX) + 'px';
    btn.style.top = (rect.top + window.scrollY) + 'px';
    btn.style.width = rect.width + 'px';
    btn.style.height = rect.height + 'px';
    btn.style.display = 'block';
    btn.style.pointerEvents = 'auto';
  }

  function init(){
    createOverlay();
    updateOverlay();
    window.addEventListener('resize', updateOverlay);
    window.addEventListener('scroll', updateOverlay, {passive:true});
    new MutationObserver(()=>updateOverlay()).observe(document.body, {childList:true, subtree:true, characterData:true});
  }

  if(document.readyState === 'loading'){ document.addEventListener('DOMContentLoaded', init); } else { init(); }
})();
